package com.fzf.org.mq.producer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.fzf.org.constants.RedisKeyConstant.BLOG_REVIEW_STREAM_GROUP_KEY;
import static com.fzf.org.constants.RedisKeyConstant.BLOG_REVIEW_STREAM_TOPIC_KEY;

/**
 * 博客审核消息生产者
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BlogReviewerProducer {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 发送博客审核消息到Redis Stream
     *
     * @param blogId 博客ID
     * @return 消息ID
     */
    public RecordId sendBlogReviewMessage(Long blogId) {
        // 1. 创建消息内容
        Map<String, String> content = new HashMap<>();
        content.put("blogId", String.valueOf(blogId));
        content.put("timestamp", String.valueOf(System.currentTimeMillis()));

        // 2. 创建Stream记录
        ObjectRecord<String, Map<String, String>> record = StreamRecords.newRecord()
                .ofObject(content)
                .withStreamKey(BLOG_REVIEW_STREAM_TOPIC_KEY);

        try {
            // 3. 确保消费者组存在
            try {
                stringRedisTemplate.opsForStream().createGroup(BLOG_REVIEW_STREAM_TOPIC_KEY, BLOG_REVIEW_STREAM_GROUP_KEY);
            } catch (Exception e) {
                log.warn("Consumer group already exists: {}", BLOG_REVIEW_STREAM_GROUP_KEY);
            }

            // 4. 发送消息到Stream
            RecordId recordId = stringRedisTemplate.opsForStream().add(record);
            log.info("Sent blog review message successfully, blogId: {}, messageId: {}", blogId, recordId);
            return recordId;
        } catch (Exception e) {
            log.error("Failed to send blog review message, blogId: {}", blogId, e);
            throw new RuntimeException("Failed to send blog review message", e);
        }
    }
}
